package com.licw.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.licw.common.utils.PageUtils;
import com.licw.common.utils.Query;

import com.licw.gulimall.product.dao.CategoryDao;
import com.licw.gulimall.product.entity.CategoryEntity;
import com.licw.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //  查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
//        组装
        List<CategoryEntity> level1Menus =
                categoryEntities.stream()
                        .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                        .map((menu)->{
                            menu.setChildren(getChildren(menu, categoryEntities));
                            return menu;
                        })
                        .sorted((category1, category2)->{
                            return (category1.getSort() == null? 0:category1.getSort()) - (category2.getSort() == null?0:category2.getSort());
                        })
                        .collect(Collectors.toList());



        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> menus) {
        //TODO 1. 检查当前删除的菜单是否被别的地方引用

        // 逻辑删除
        baseMapper.deleteBatchIds(menus);
    }

    // 递归查找当前菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> categories){
        List<CategoryEntity> children = categories.stream().filter(categoryEntity -> {
                    return Objects.equals(categoryEntity.getParentCid(), root.getCatId());
                })
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, categories));
                    return categoryEntity;
                })
                .sorted((category1, category2)->{
                    return (category1.getSort() == null? 0:category1.getSort()) - (category2.getSort() == null?0:category2.getSort());
                })
                .collect(Collectors.toList());

        return children;
    }

}